package com.liss.boot.java8.optional;

import java.util.Optional;

class User {
    private Address address;
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }


}

class Address {
    private String city;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

public class OptionalDemo {

    //以前
    public String getCity(User user) throws Exception {
        if (user != null) {
            if (user.getAddress() != null) {
                Address address = user.getAddress();
                if (address.getCity() != null) {
                    return address.getCity();
                }
            }
        }
        throw new Exception("取值错误");
    }

    public String getCity8(User user) throws Exception {
        return Optional.ofNullable(user)
                .map(u -> u.getAddress())
                .map(a -> a.getCity())
                .orElseThrow(() -> new Exception("取指错误"));
    }

    /**
     *
     例3
     if(user!=null){
     dosomething(user);
     }
     Optional.ofNullable(user)
     .ifPresent(u->{
     dosomething(u);
     });
     */
    public User getUser(User user) throws Exception {
        if (user != null) {
            String name = user.getName();
            if ("zhangsan".equals(name)) {
                return user;
            }
            return null;
        } else {
            user = new User();
            user.setName("zhangsan");
            return user;
        }
    }

    public User getUser8(User user) {
        return Optional.ofNullable(user)
                .filter(u -> "zhangsan".equals(u.getName()))
                .orElseGet(() -> {
                    User user1 = new User();
                    user1.setName("zhangsan");
                    return user1;
                });
    }
}
